#pragma warning (disable:4786)

#include "Block.h"
#include "Message.h"
#include "QuakeServer.h"



Block::Block(FILE* file) : Buffer(file),m_IsLast(false),m_Time(0),m_pClientData(NULL)
{

	Reset();
	Parse();
}

bool Block::Write(FILE* file)
{
	Unparse();
	Reset();
	return Buffer::Write(file);
}


Block::~Block()
{
	Messages::iterator it;
	for (it = m_Messages.begin(); it != m_Messages.end(); it++)
	{
		delete (*it);
	}
}

Block::Block(const Block& other) : 
	Buffer(other),m_Time(other.m_Time),m_IsLast(other.m_IsLast),m_pClientData(NULL)
	
{
	Messages::const_iterator it;
	for (it = other.m_Messages.begin(); it != other.m_Messages.end(); it++)
	{
		Message* pMsg = (*it)->Clone();

		AddMessage(pMsg);
		if (pMsg->IsClientData())
			m_pClientData = (MessageClientdata*)pMsg;

	}
	
}


Block& Block::operator=(const Block& Other)
{
	if (&Other != this)
	{
		Buffer::operator=(Other);
		Messages::const_iterator it;
		for (it = Other.m_Messages.begin(); it != Other.m_Messages.end(); it++)
		{
			AddMessage((*it)->Clone());
		}
		m_IsLast = Other.m_IsLast;
		m_Time = Other.m_Time;
	}

	return *this;
}

void Block::Parse()
{
	while (Buffer::HasMore())
	{
		Message* pMessage = Message::LoadMessage(*this);
		if (!pMessage)
			continue;
		if (pMessage->IsClientData())
			m_pClientData = (MessageClientdata*)pMessage;

		m_Messages.push_back(pMessage);
	}
}

void Block::Unparse()
{
	Reset(true);

	Messages::iterator it;
	for (it = m_Messages.begin(); it != m_Messages.end(); it++)
	{
		(*it)->WriteTo(*this);
	}

	Reset();
}


void Block::AddMessage(Message* NewMessage)
{
	m_Messages.push_back(NewMessage);
}

void Block::RenumberEntity(int OldId, int NewId)
{
	Messages::iterator it;
	for (it = m_Messages.begin(); it != m_Messages.end(); it++)
	{
		(*it)->RenumberEntity(OldId,NewId);
	}
}


void Block::ShiftEntity(int Id, int Offset[3])
{
	Messages::iterator it;
	for (it = m_Messages.begin(); it != m_Messages.end(); it++)
	{
		(*it)->ShiftEntity(Id,Offset);
	}
}

void Block::MergeInto(Block& pOther,int ClientNumber)
{
	Messages::iterator it;
	for (it = m_Messages.begin(); it != m_Messages.end(); it++)
	{
		(*it)->MergeInto(pOther,ClientNumber);
	}
}

MessageUpdateEntity* Block::GetUpdateFor(int EntityId)
{
	Messages::iterator it;
	for (it = m_Messages.begin(); it != m_Messages.end(); it++)
	{
		if ((*it)->IsUpdateFor(EntityId))
			return (MessageUpdateEntity*)*it;
	}
	return NULL;
}

